<template>
  <div class="custom-portrait">
    <!-- 返回按钮 -->
    <!-- <div class="back">
      <i class="el-icon-arrow-left" @click="$router.go(-1)">返回</i>
    </div> -->
    <!-- 整体样式 -->
    <div class="component-container">
      <!-- 上部分 -->
      <div class="drawcontainer">
        <div class="content-box" style="padding:0 20px;margin-top:0;">
          <p>基本信息</p>
          <div class="headtext">
            <HkForm
              ref="hkFormRef"
              label-width="140"
              :form-labels="formObj.formLabels"
              :rules="formObj.formRules"
              :data="formData"
              :dict-list="formObj.dictList"
              :btn-hidden="true"
              label-position="left"
              @handleEvent="handleEvent"
            />
          </div>
        </div>

        <!-- 隐藏内容区域 -->

        <div class="content-box" style="padding:0 20px;flex:1">
          <!-- tabs -->
          <!-- <el-tab-pane label="属性信息"> -->
          <p>监测策略</p>
          <div class="tab-content">
            <!--                <el-button size="mini" type="primary">创建模型</el-button>-->
            <el-button type="primary" @click="handleBtn">配置策略</el-button>
          </div>
          <HkTable
            :loading="loading"
            :table-data="tableList"
            :table-columns="tableFieldList"
            :show-pag="true"
            :is-need-index="true"
            :show-index="true"
            :query-params="queryParams"
            rowkey="id"
            :total="total"
            @changePage="changePage"
          >
            <template #status="scope">
              <span :class="[scope.row.status ? 'red' : 'green', 'circle']">{{
                scope.row.status == 0 ? '关闭' : '开启'
              }}</span>
            </template>
          </HkTable>
          <!-- </el-tab-pane> -->

        </div>
      </div>
    </div>
    <!-- 底部 -->
    <div class="component-footer">
      <el-button type="primary" @click="handleSubmit">保 存</el-button>
      <el-button @click="$router.go(-1)">取 消</el-button>
    </div>
    <!-- <edit-form ref="dialogRef" title="编辑" :is-edit="true" :form="formData" @handleSubmit="getEditData" /> -->
  </div>
</template>
<script>
// import EditForm from './components/edit.vue'
import { detail, getTableData } from '@/api/icp/monitoring'
import HkTable from '@/components/Hk-Table'
import HkForm from '@/components/Hk-Form'
import { getMetrics, editMetricsBase } from '@/api/icp/monitoring'
import _ from 'lodash'

export default {
  components: { HkTable, HkForm },
  beforeRouteLeave(to, from, next) {
    to.meta.keepAlive = true
    next()
  },
  data() {
    return {
      loading: false,
      // detailData: {
      //   metricsName: '',
      //   normalCode: '',
      //   eventType: ''
      // },
      tableData: [],
      date: 'day',
      value2: '',
      metricsBaseCode: '',
      formData: {},
      queryParams: {
        name: '',
        aliasType: '',
        metricsCode: '',
        current: 1,
        size: 10
      },
      total: 0,
      tableList: [],
      tableFieldList: [
        { label: '名称', param: 'name' },
        { label: '状态', param: 'status', width: '340', type: 'slot' }
      ],
      //  表单
      formObj: {
        formLabels: [
          {
            label: '事件名称',
            field: 'metricsName',
            type: 'input',
            span: 12
          },
          // {
          //   label: '事件简称',
          //   field: 'malName',
          //   type: 'input',
          //   span: 12
          // },
          {
            label: '指标来源',
            field: 'metrics_source',
            type: 'select',
            list: 'metrics_source_list',
            span: 12
          },
          // {
          //   label: '是否展示',
          //   field: 'isDisplay',
          //   type: 'radio',
          //   list: 'isDisplayList',
          //   span: 24
          // },
          {
            label: '事件级别',
            field: 'event_level',
            type: 'select',
            list: 'event_level_list',
            span: 12
          },
          {
            label: '事件分类',
            field: 'event_category',
            type: 'select',
            list: 'event_category_list',
            span: 12,
            attrs: {
              'show-all-levels': false
            }
          },
          // {
          //   label: '对象分类',
          //   field: 'object_category',
          //   type: 'select',
          //   list: 'object_category_list',
          //   span: 12
          // },
          {
            label: '风险分类',
            field: 'risk_type',
            type: 'select',
            list: 'risk_type_list',
            span: 12
          },
          {
            label: '事件类型',
            field: 'event_type',
            type: 'cascader',
            list: 'event_type_list',
            props: { checkStrictly: false },
            span: 12
          },
          {
            label: '分保技术要求',
            field: 'bm_category',
            type: 'cascader',
            list: 'bm_category_list',
            span: 12
          },
          // {
          //   label: '分保技术要求小类',
          //   field: 'protect_sub_category',
          //   type: 'select',
          //   list: 'protect_sub_category_list',
          //   span: 12
          // },
          {
            label: '行为类别',
            field: 'behavior_type',
            type: 'select',
            list: 'behavior_type_list',
            span: 12
          },
          {
            label: '监管对象',
            field: 'entity_type',
            type: 'select',
            list: 'entity_type_list',
            span: 12
          },
          {
            label: '行业属性',
            field: 'industry_type',
            type: 'select',
            list: 'industry_type_list',
            span: 12
          },
          {
            label: '一票否决项',
            field: 'veto_status',
            type: 'select',
            list: 'veto_status_list',
            span: 12
          },
          {
            label: '建议处置时限',
            field: 'dispose_time_range',
            type: 'select',
            list: 'dispose_time_range_list',
            span: 12
          }
        ],
        dictList: {
          isDisplayList: [
            { label: '是', value: 1 },
            { label: '否', value: 0 }
          ],
          event_level_list: [],
          event_category_list: [],
          risk_type_list: [],
          event_type_list: [],
          bm_category_list: [],
          // protect_sub_category_list: [],
          behavior_type_list: [],
          entity_type_list: [],
          industry_type_list: [],
          veto_status_list: [],
          overtime_rule_list: []
        },
        formRules: {
          metricsName: [{ required: true, message: '请输入事件名称', trigger: 'blur' }],
          metricsCode: [
            { required: true, message: '请输入事件编码', trigger: 'blur' },
            { validator: this.checkNormalCode, trigger: 'blur' }
          ],
          event_level: [{ required: true, message: '请选择事件级别', trigger: 'blur' }],
          event_category: [{ required: true, message: '请选择事件分类', trigger: 'blur' }],
          risk_type: [{ required: true, message: '请选择风险分类', trigger: 'blur' }],
          event_type: [{ required: true, message: '请选择事件类型', trigger: 'blur' }],
          bm_category: [{ required: true, message: '请选择分保技术要求', trigger: 'blur' }],
          behavior_type: [{ required: true, message: '请选择行为类别', trigger: 'blur' }],
          entity_type: [{ required: true, message: '请选择监管对象', trigger: 'blur' }],
          industry_type: [{ required: true, message: '请选择行业属性', trigger: 'blur' }],
          veto_status: [{ required: true, message: '请选择一票否决项', trigger: 'blur' }]
        }
      }
    }
  },
  created() {
    this.metricsBaseCode = this.$route.query.metricsBaseCode
    this.queryParams.metricsCode = this.metricsBaseCode
    this.getSelectList()
    this.getEditData()
    this.getTableList()
  },
  methods: {
    // 获取编辑信息
    handleEdit() {
      this.getEditData()
      this.$refs.dialogRef.show()
    },
    // 获取编辑数据
    getEditData() {
      detail(this.metricsBaseCode).then((res) => {
        let result = {}
        res.metricsDictRefs.forEach((i, index) => {
          const value = i.dictValue.split(',')
          result[i.groupCode] = value && value.length === 1 ? value[0] : value
        })
        result = Object.assign({}, result, {
          id: res.id,
          metricsCode: res.metricsCode,
          metricsName: res.metricsName
        })

        this.formData = result
      })
    },
    /** 获取下拉列表数据*/
    getSelectList() {
      getMetrics().then((res) => {
        const result = res
        result.forEach((item) => {
          this.formObj.dictList[item.dictValue + '_list'] = this.handleRestructure(item)
        })
      })
    },
    /** 重构数据类型 */
    handleRestructure(data) {
      if (data?.children.length > 0) {
        return data.children.map((i) => {
          return { label: i.dictKey, value: i.dictValue, id: i.id, children: this.handleRestructure(i) }
        })
      }
    },
    /** 级联选的值*/
    handleEvent(obj, subValue) {

    },
    /** 获取属性信息中的数据*/
    getTableList() {
      this.loading = true
      this.queryParams.scrollToTop = true
      getTableData(this.queryParams).then((res) => {
        this.tableList = res.list
        this.total = res.total
        this.loading = false
        this.queryParams.scrollToTop = false
      })
    },
    /**  分页 */
    changePage() {
      this.getTableList()
    },
    handleBtn() {
      this.$router.push(window.prefix + '/icp/rule?name=icpHome')
    },
    /** 提交 */
    handleSubmit() {
      this.$refs.hkFormRef.handleFormSubmit('formLabels').then((res) => {
        const keys = Object.keys(res)
        const tags = []
        keys.forEach((i) => {
          if (
            i !== 'metricsName' &&
            i !== 'metricsCode' &&
            this.formObj.dictList[i + '_list']
          ) {
            const normalCode = res[i] instanceof Array ? res[i] : [res[i]]
            tags.push({
              groupCode: i,
              dictId: this.getIdByCode(this.formObj.dictList[i + '_list'], _.cloneDeep(res[i])),
              dictValue: [...normalCode].join(',')
            })
          }
        })
        this.submitData = {
          metricsName: res.metricsName,
          metricsCode: res.metricsCode,
          metricsDictRefs: tags
        }
        editMetricsBase(this.submitData).then((res) => {
          this.$message.success('保存成功')
          this.resetForm()
          this.$router.go(-1)
          this.$emit('handleSubmit')
        })
      })
    },
    /** 校验 */
    checkNormalCode(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入标识符'))
      }
      const reg = /^([0-9\-])*$/
      if (!reg.test(value)) {
        callback(new Error('输入内容只能是数字与-！'))
      } else {
        callback()
      }
    },
    getIdByCode(list, codes) {
      let code = codes
      if (codes instanceof Array) {
        code = codes.shift()
      }
      const item = list.find(o => o.value === code)
      if (item.children && item.children.length > 0 && codes.length > 0) {
        return this.getIdByCode(item.children, codes)
      }
      return item.id
    }
  }
}
</script>

<style lang="scss" scoped>
#app.dark-theme {
  .custom-portrait {
    background: #092253 !important;
  }

  .component-footer {
    background: transparent
  }

  .back {
    border-bottom: 1px solid rgba(0, 225, 228, .2);
  }

  .el-table__header-wrapper th {
    border-bottom: 1px solid rgba(0, 225, 228, .2) !important;
  }
}

::v-deep .el-form-item {
  margin-bottom: 10px !important;
}

::v-deep .targetTable {
  flex: 1 !important;
}

.custom-portrait {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #eef0f5;
  // 返回按钮
  .back {
    line-height: 40px;
    height: 40px;
    border-bottom: 1px solid #e9e9e9;
    color: #4B6EEF;
    padding: 0 15px;
  }

  .component-container {
    flex: 1;
    overflow: hidden;
    width: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
    // 顶部
    .drawcontainer {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;

      .drawheader {
        background-color: #fdfdfd;
        border-radius: 6px;

        // 文字区域
        .headtext {
          width: 100%;
          display: flex;
          align-items: center;
          padding: 20px 20px 0;

          img {
            float: left;
            padding-right: 20px;
            height: 100px;
            margin: 20px;
          }

          .headtitle {
            white-space: nowrap;
            font-weight: 700;
            font-style: normal;
            font-size: 16px;
            color: #303032;
            padding-top: 20px;
            width: 100%;
          }

          .headcontent {
            display: inline-block;
            margin-top: 20px;
            width: 100%;

            .headbox {
              display: inline-block;
              width: 16%;
              float: left;
              padding-right: 20px;

              .boxtitle {
                margin-top: 0;
                width: 100%;
                height: 14px;
                margin-bottom: 20px;
                font-size: 14px;
                color: #505255;
              }

              .boxcontent {
                font-size: 14px;
                width: 100%;
                margin-bottom: 20px;
                font-size: 14px;
                color: #303032;
                overflow: hidden;
                display: inline-block;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }
          }
        }
      }

      .content-box {
        // height: 100%;
        width: 100%;
        overflow: hidden;
        background: #fff;
        margin-top: 20px;
        border-radius: 6px;
        box-sizing: border-box;

        p {
          margin: 10px 0;
          font-size: 16px;
          font-weight: 600;
        }

        .drawmain {
          overflow-y: auto;
          background-color: #fff;
          width: 100%;
          height: 100%;
          box-sizing: border-box;
        }

        .business-data-title {
          margin-bottom: 10px;
        }

        &:nth-child(2) {
          display: flex;
          flex-direction: column;
        }
      }
    }

    .tab-content {
    }

    .hk-container {
      width: 100%;
      height: 100%;

      padding: 10px;
      display: flex;
      justify-content: center;
    }

    .opt-btn {
      text-align: center;
      -webkit-transform: translateY(-2px);
      transform: translateY(-2px);
      position: absolute;
      left: 48%;
      z-index: 1;
    }
  }

  .component-footer {
    // margin-top:20px;
    // background:#fff;
    padding: 20px 0 0 0;
    text-align: right
  }
}

::v-deep .el-form-item {
  margin-bottom: 20px;
}

// 去掉中间的外边距
.el-button + .el-button {
  margin-left: 10px;
}

.dateFilter {
  display: flex;
  justify-content: flex-start;
  height: 32px;
  margin-left: 7px;
}
</style>
<style lang="scss" scoped>
// 卡片部分
.custom-portrait {
  .el-card {
    height: 100%;
  }

  .el-card__header {
    padding: 16px 12px 0 12px;
    position: relative;
    border: none;

    &::before {
      content: '';
      width: 4px;
      height: 14px;
      background: #2979ff;
      position: absolute;
      left: 0;
      top: 18px;
    }

    .el-card-title {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 14px;
      color: #303032;
      font-weight: 700;
    }

    .el-card-label {
      font-size: 12px;
      color: #95989c;
      font-weight: 400;
      padding-top: 8px;
    }

    .el-select {
      width: 67%;
      margin-right: 4%;
      text-align: left;
    }

    .el-card__body {
      padding: 0;
      height: calc(100% - 53px);
    }
  }

  .el-tabs__content,
  .el-table {
    height: 100%;
  }

  .el-tab-pane {
    height: 100%;
  }
}

.circle:before {
  content: '';
  display: inline-block;
  vertical-align: middle;
  height: 8px;
  width: 8px;
  border-radius: 50%;
  background-color: #cb9900;
  margin-right: 5px;
}

.red:before {
  background: #fa541c !important;
}

.green:before {
  background: #3abf81 !important;
}

.el-icon-arrow-left {
  cursor: pointer;
}
</style>
